const http = require('../../utils/http.js')
const util = require('../../utils/util.js')
const Base64 = require('../../utils/base64.js')

Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgUrl: http.imgUrl,
        showPoster: true,
        nav: '4',
        fromOthor: false,
        navList: [{
                id: '1',
                nav: '简介'
            },
            {
                id: '2',
                nav: '目录'
            },
            {
                id: '3',
                nav: '讨论'
            },
            {
                id: '4',
                nav: '考试'
            }
        ],
        navBar: {
            title: '课程详情',
            btn: 'goBack'
        },
        showNav: false,
        discussNav: '1',
        inputArr: [],
        return_eval: false,
        eval: false,
        initialTime: 0,
        startTime: '00:00',
        endTime: '00:00',
        discussList:[]
    },
    modelHide() {
      this.setData({
        tipsModals: {
          show: false,
        }
      })
    },
    delInfoConfirm(){
      this.setData({
        tipsModals: {
          show: false,
        }
      })
      wx.navigateTo({
        url: '/pages/account/setting/setting',
      })
      
    },
    /**
     * 播放视频
     */
    playVideo() {
        let that = this,
            tv_url = that.data.tv_url;
        wx.getNetworkType({
            success: res => {
                let is_allow = wx.getStorageSync('is_allow') || 1
                var networkType = res.networkType;
                let flag1 = (is_allow == 1 && networkType == 'wifi') || is_allow == 2?true:false;
                // console.log(is_allow)
                if (flag1 && tv_url) {
                    that.videoContext.play()
                    that.setData({
                        showPoster: false
                    })
                }else{
                    that.setData({
                      tipsModals: {
                        show: true,
                        ont:'网络提示',
                        txt: '您不处于WIFI状态,请在账号设置打开,允许在数据流量环境观看',
                        cancel: 'modelHide',
                        ok: 'delInfoConfirm',
                      }
                    })
                }
            }
        })
    },

    /**
     * 获取视频时长和已播放节点
     */
    getVideoTime(e) {
        let currentTime = e.detail.currentTime,
            duration = e.detail.duration
        // console.log(util)
        this.setData({
            prograss: (currentTime / duration) * 100,
            initialTime: currentTime,
            startTime: util.formatSeconds(currentTime),
            endTime: util.formatSeconds(duration)
        })
    },

    /**
     * 结束/暂停播放显示封面图
     */
    showPoster() {
        this.setData({
            showPoster: true
        })
    },

    /**
     * 返回
     */
    goBack() {
        http.goBack()
    },

    /**
     * 切换导航
     */
    changeNav(e) {
        let id = e.currentTarget.dataset.id,
            that = this
        that.setData({
            nav: id
        })
        switch (id) {
            case '1':
                that.getIntroduction() // 获取课程简介
                break
            case '2':
                that.getThreadList() // 获取课程目录
                break
            case '3':
                that.getPostList(0) // 获取课程评论列表
                that.setData({
                    nullData: {
                        img: http.imgUrl + 'null_data_1.jpg',
                        txt: '暂时没有评论内容'
                    }
                })
                break
            case '4':
                that.getLessonTest(0) // 获取课程考试列表
                break
        }
    },

    /**
     * 加入课堂确认支付
     */
    goPay() {
        let id = this.data.lid,
            id_str = this.data.id_str;
            console.log(this.data)
            console.log(id)
            console.log(id_str)
        wx.setStorageSync('aid', '0')
        wx.navigateTo({
            url: '/pages/course/pay/pay?id=' + id + '&id_str=' + id_str,
        })
    },

    /**
     * 到课程试看
     */
    goTrySee(e) {
        let lid = e.currentTarget.dataset.lid,
            nid = e.currentTarget.dataset.nid,
            tid = e.currentTarget.dataset.tid,
            name = e.currentTarget.dataset.name
        wx.navigateTo({
            url: '/pages/course/trysee/trysee?lid=' + lid + '&nid=' + nid + '&tid=' + tid + '&name=' + name,
        })
    },

    /**
     * 切换讨论导航
     */
    changeDiscussNav(e) {
        let id = http.dataIndex(e)[1],
            that = this
        this.setData({
            discussNav: id
        })
        if (id === '1') {
            that.getPostList(0) // 获取课程评论列表
            that.setData({
                nullData: {
                    img: http.imgUrl + 'null_data_1.jpg',
                    txt: '暂时没有评论内容'
                }
            })
        } else {
            that.getStarList(0) // 获取课程评分列表
            that.setData({
                nullData: {
                    img: http.imgUrl + 'null_data_1.jpg',
                    txt: '暂无评分'
                }
            })
        }
    },

    /**
     * 回复评论
     */
    returnEval(e) {
        let pid = e.currentTarget.dataset.pid,
            spid = e.currentTarget.dataset.spid,
            tpid = e.currentTarget.dataset.tpid
        this.setData({
            return_eval: true,
            pid: pid,
            spid: spid,
            tpid: tpid
        })
    },

    /**
     * 关闭回复评论
     */
    closeReturnEval() {
        this.setData({
            return_eval: false
        })
    },

    /**
     * 评价
     */
    eval() {
      var that = this
      this.setData({
        eval: true
      })
      var a = true
      setTimeout(function () {
        that.setData({
          atrue: true
        })
      }, 200

      )
    },

    /**
     * 关闭评价
     */
    closeEval() {
        this.setData({
            eval: false
        })
    },

    /**
     *  获取评价以及回复
     */
    inputTxt(e) {
        let inputArr = this.data.inputArr
        let temp = http.inputArr(inputArr, e)
        // console.log(temp)
        this.setData({
            inputArr: temp
        })
    },

    /**
     * 去评分
     */
    goDisScore(e) {
        let id = this.data.lid
        // console.log(id)
        wx.navigateTo({
            url: '/pages/course/disScore/disScore?id=' + id,
        })
    },

    /**
     * 到考试
     */
    goTest(e) {
        let id = http.dataIndex(e)[1]
        // console.log(http.dataIndex(e))
        // console.log(id)
        let that = this,
        url = 'Test_getTestInfo',
        token = wx.getStorageSync('token')
        http._post(
          url,
          {token:token,ltid:id},
          res=>{
            //  console.log(res.data)
             var data = res.data
             if(res.data.re==='0'){
                wx.showToast({
                  title: res.data.info,
                  icon:"none",
                  duration:3000
                })
             }else{
                wx.navigateTo({
                url: '/pages/course/test/test?id=' + id
              })
             }
          }
        )
        // wx.navigateTo({
        //     url: '/pages/course/test/test?id=' + id
        // })
    },
    /**
     * 下拉加载课程评论
     */
    onReachBottom:function () {
        var is_page = this.data.is_page
        var sum_page = this.data.sum_page
        if (is_page >= sum_page){
            return false
        }else{
            this.getPostList2(is_page++)
        }
    },
    /**
     * 获取课程评论
     */
    getPostList2(p) {
        let that = this,
            token = wx.getStorageSync('token'),
            url = 'Lesson_getPostList',
            lid = that.data.lid
            
        http._post(
            url,
             { token: token, lid: lid, page: p },
            res => {
                console.log(res.data)
                let data = res.data
                let list = that.data.discussList 
                if (data.re === '1') {
                    for (var a = 0; a < data.data.list.length;a++){
                        list.push(data.data.list[a])
                    }
                    that.setData({
                        discussList: list,
                        is_page: data.data.is_page,
                        page: data.data.page,
                        sum_page: data.data.sum_page
                    })
                } else {
                    that.setData({
                        discussList: []
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },
    /**
    * 获取课程评论
    */
    getPostList(p) {
        let that = this,
            token = wx.getStorageSync('token'),
            url = 'Lesson_getPostList',
            lid = that.data.lid
        http._post(
            url,
            { token: token, lid: lid, page: p },
            res => {
                let data = res.data
                if (data.re === '1') {
                    that.setData({
                        discussList: data.data.list,
                        is_page: data.data.is_page,
                        page: data.data.page,
                        sum_page: data.data.sum_page
                    })
                } else {
                    that.setData({
                        discussList: []
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 提交评价
     */
    confirmEval() {
        let that = this,
            token = wx.getStorageSync('token'),
            lid = that.data.lid,
            inputArr = that.data.inputArr,
            content = inputArr[1],
            url = 'Lesson_lessonPost'

        if (!http.ifEmpty(content)) {
            wx.showToast({
                title: '请输入评论内容',
                icon: 'none',
                duration: 1000
            })
            return
        }

        http._post(
            url, { token: token, lid: lid, content: content },
            res => {
                // console.log(res.data)
                wx.showToast({
                    title: res.data.info,
                    icon: 'none',
                    duration: 1000
                })
                if (res.data.re === '1') {
                    that.closeEval()
                    that.getPostList(0)
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 回复评价
     */
    confirmReturn() {
        let that = this,
            token = wx.getStorageSync('token'),
            lid = that.data.lid,
            inputArr = that.data.inputArr,
            content = inputArr[0],
            pid = that.data.pid,
            spid = that.data.spid,
            tpid = that.data.tpidpid,
            url = 'Lesson_lessonPost'

        if (!http.ifEmpty(content)) {
            wx.showToast({
                title: '请输入评论内容',
                icon: 'none',
                duration: 1000
            })
            return
        }

        http._post(
            url, { token: token, lid: lid, pid: pid, spid: spid, tpid: tpid, content: content },
            res => {
                // console.log(res.data)
                wx.showToast({
                    title: res.data.info,
                    icon: 'none',
                    duration: 1000
                })
                if (res.data.re === '1') {
                    that.closeReturnEval()
                    that.getPostList(0)
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 获取课程评分
     */
    getStarList(p) {
        let that = this,
            token = wx.getStorageSync('token'),
            url = 'Lesson_getStarList',
            lid = that.data.lid

        http._post(
            url, { token: token, lid: lid, page: p },
            res => {
                // console.log(res.data)
                let data = res.data
                if (data.re === '1') {
                    let temp_star = []
                    for (let item of data.data.list) {
                        temp_star.push(Number(item.star))
                    }
                    that.setData({
                        discussScoreList: data.data.list,
                        star: temp_star,
                        is_page: data.data.is_page,
                        page: data.data.page,
                        sum_page: data.data.sum_page
                    })
                } else {
                    that.setData({
                        discussScoreList: []
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 评论点赞
     */
    recommendEval(e) {
        let that = this,
            url = 'Lesson_userStart',
            token = wx.getStorageSync('token'),
            id = http.dataIndex(e)[1],
            reEval = that.data.reEval

        if (reEval > 0) {
            wx.showToast({
                title: '操作过于频繁，请五秒后重试',
                icon: 'none',
                duration: 1000
            })

            return
        }

        http._post(
            url, { token: token, type: 3, id: id },
            res => {
                // console.log(res.data)
                wx.showToast({
                    title: res.data.info,
                    icon: 'none',
                    duration: 1000,
                    success: function() {
                        setTimeout(function() {
                            that.getPostList(0) // 获取课程评论列表
                        }, 1000)
                    }
                })
                let time = 5,
                    timeCount = setInterval(function() {
                        time--
                        that.setData({
                            reEval: time
                        })
                        if (time === 0) {
                            clearInterval(timeCount)
                        }
                    }, 1000)
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 评论取消点赞
     */
    cancelRecommendEval(e) {
        let that = this,
            url = 'Lesson_userStart',
            token = wx.getStorageSync('token'),
            id = http.dataIndex(e)[1],
            reEval = that.data.reEval

        if (reEval > 0) {
            wx.showToast({
                title: '操作过于频繁，请五秒后重试',
                icon: 'none',
                duration: 1000
            })

            return
        }

        http._post(
            url, { token: token, type: 3, id: id, del: 1 },
            res => {
                // console.log(res.data)
                wx.showToast({
                    title: res.data.info,
                    icon: 'none',
                    duration: 1000,
                    success: function() {
                        setTimeout(function() {
                            that.getPostList(0) // 获取课程评论列表
                        }, 1000)
                    }
                })
                let time = 5,
                    timeCount = setInterval(function() {
                        time--
                        that.setData({
                            reEval: time
                        })
                        if (time === 0) {
                            clearInterval(timeCount)
                        }
                    }, 1000)
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 获取课程简介
     */
    getIntroduction() {
        let that = this,
            token = wx.getStorageSync('token'),
            lid = that.data.lid,
            url = 'Lesson_formIntroduction'
            // console.log(that.data)
        // wx.showLoading({
        //     title: '加载中……',
        //     mask: true
        // })

        http._post(
            url, { token: token, lid: lid },
            res => {
                console.log(res.data)
                let data = res.data
                wx.hideLoading()
                if (data.re === '1') {
                    let material = data.data.materialList,
                        temp_arr = []

                    for (let item of material) {
                        temp_arr.push(item.lid)
                    }
                    temp_arr.join(',')
                    that.setData({
                        introduce: data.data,
                        starNumber: Number(data.data.star),
                        id_str: temp_arr
                    })
                //   console.log(Number(data.data.star))
                } else {
                    wx.showToast({
                        title: data.info,
                        icon: 'none',
                        duration: 1000
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 获取视频播放链接
     */
    getVideourl() {
        let that = this,
            url = 'Lesson_getVideourl',
            token = wx.getStorageSync('token'),
            lid = that.data.lid

        http._post(
            url, { token: token, lid: lid },
            res => {
                console.log(res.data)
                let data = res.data
                if (data.re === '1') {
                    let temp_url = Base64.CusBASE64.decoder(data.data.tv_url).replace("UNO", "").replace("HACHA", ""),
                        endTime = data.data.test_time_two

                    that.setData({
                        tv_url: temp_url,
                        endTime: endTime
                    })
                } else {
                    wx.showToast({
                        title: data.info,
                        icon: 'none',
                        duration: 1000
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 获取课程目录
     */
    getThreadList() {
        let that = this,
            lid = that.data.lid,
            url = 'Lesson_formThreadList'

        http._post(
            url, { lid: lid },
            res => {
                // console.log(res.data)
                let data = res.data
                if (data.re === '1') {
                    that.setData({
                        catalogList: data.data.titleList,
                        try_look: data.data.titleList[0].try_look
                    })
                } else {
                    that.setData({
                        catalogList: []
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 获取课程考试列表
     */
    getLessonTest(p) {
      console.log(p)
        let that = this,
            url = 'Test_getLessonTest',
            token = wx.getStorageSync('token'),
            lid = that.data.lid

        http._post(
            url, { token: token, lid: lid, page: p },
            res => {
                // console.log(res.data)
                let data = res.data
                if (data.re === '1') {
                    that.setData({
                        testList: data.data.list,
                        is_page: data.data.is_page,
                        page: data.data.page,
                        sum_page: data.data.sum_page
                    })
                } else {
                    that.setData({
                        testList: []
                    })
                }
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 想学
     */
    toLearn() {
        let that = this,
            url = 'Lesson_userStart',
            token = wx.getStorageSync('token'),
            id = that.data.lid,
            leEval = that.data.leEval

        if (leEval > 0) {
            wx.showToast({
                title: '操作过于频繁，请五秒后重试',
                icon: 'none',
                duration: 1000
            })

            return
        }

        http._post(
            url, { token: token, type: 2, id: id },
            res => {
                console.log(res)

                let data = res.data
                wx.showToast({
                    title: '您收藏添加成功',
                    icon: 'none',
                    duration: 1000,
                    success: function() {
                        setTimeout(function() {
                            that.getIntroduction() // 获取课程简介
                        }, 200)
                    }
                })
                let time = 5,
                    timeCount = setInterval(function() {
                        time--
                        that.setData({
                            leEval: time
                        })
                        if (time === 0) {
                            clearInterval(timeCount)
                        }
                    }, 1000)
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 取消想学
     */
    cancelToLearn() {
        let that = this,
            url = 'Lesson_userStart',
            token = wx.getStorageSync('token'),
            id = that.data.lid,
            leEval = that.data.leEval

        if (leEval > 0) {
            wx.showToast({
                title: '操作过于频繁，请五秒后重试',
                icon: 'none',
                duration: 1000
            })

            return
        }

        http._post(
            url, { token: token, type: 2, id: id, del: 1 },
            res => {
                console.log(res.data)

                let data = res.data
                wx.showToast({
                    title: "您取消收藏成功",
                    icon: 'none',
                    duration: 1000,
                    success: function() {
                        setTimeout(function() {
                            that.getIntroduction() // 获取课程简介
                          wx.reLaunch({
                              url:"/pages/index/index"
                            })
                        }, 1000)
                    }
                })
                let time = 5,
                    timeCount = setInterval(function() {
                        time--
                        that.setData({
                            leEval: time
                        })
                        if (time === 0) {
                            clearInterval(timeCount)
                        }
                    }, 1000)
            },
            err => {
                console.log(err)
            }
        )
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
        this.videoContext = wx.createVideoContext('course_video') // 视频播放

        console.log(options)

        let that = this
        if (options.nav) { // 是否是从购买课程成功跳转
            this.getThreadList() // 获取课程目录
            that.setData({
                fromOthor: true
            })
        }
        let nav = options.nav || '1'
        that.setData({
            nav: nav
        })

        let id = options.id || '0'
        this.setData({
            lid: id
        })
        // console.log(id)

        this.getIntroduction() // 获取课程简介
        this.getVideourl() // 获取视频播放链接

        // this.getLessonTest(0)  // 获取课程考试列表
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

        // this.getIntroduction()  // 课程简介
        // this.getVideourl()  // 视频播放链接

        // this.getLessonTest(0)  // 课程考试列表

        // this.getThreadList()  // 课程目录
        this.getStarList(0) // 课程评分列表
        // this.getPostList(0)  // 课程评论列表              
    },

    /**
     * 页面滚动事件
     */
    onPageScroll: function(Object) {
        // console.log(Object)
        let that = this
        if (Object.scrollTop > 210) {
            that.setData({
                showNav: true
            })
        } else {
            that.setData({
                showNav: false
            })
        }
    }
})